<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Core_Plugin_Core extends Zend_Controller_Plugin_Abstract
{
	protected $template,$layout,$view,$run = false;

  public function routeStartup(Zend_Controller_Request_Abstract $request)
  {
		/*
		 * Subfolder Routing
		 */
		/*
		$front = Zend_Controller_Front::getInstance();
		$front->getRouter()->addRoute('module/subfolder', 
			new Core_Controller_Router_Route_Module(array(), 
				$front->getDispatcher(), $front->getRequest()));
		*/
  }
 
  public function routeShutdown(Zend_Controller_Request_Abstract $request)
  {
		$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
		$options = $bootstrap->getOptions();
		$param = $request->getParams();
		/*
		 * Template system
		 */
		$this->template = Core_Templates::getInstance()->setOptions(@$options['template']);

		/* Layout */
		$this->layout = is_null(Zend_Layout::getMvcInstance())
											?Zend_Layout::startMvc($bootstrap->getOptions())
											:Zend_Layout::getMvcInstance();

		if(!$this->layout instanceof Zend_Layout)
			throw new Zend_Application_Exception('Layout must be extends Zend_Layout');

		$this->layout->setLayout($this->template->getLayout());
		$this->layout->setLayoutPath($this->template->getPath());

		/* View */
		$this->view = $bootstrap->getResource('view');
		$this->view = is_null($this->view)
										?new Zend_View($bootstrap->getOptions())
										:$this->view;

		if(!$this->view instanceof Zend_View)
			throw new Zend_Application_Exception('View must be extends Zend_View');
			
		Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')->setView($this->view);
		
		/* Translator */
		Core_Translate::load(array(
			'adapter' => 'array',
			'content' => @$options['languages']['dir'],
			'locale'  => 'vi',
			'scan' 		=> Zend_Translate::LOCALE_DIRECTORY
		));
		Zend_Validate_Abstract::setDefaultTranslator(Core_Translate::getInstance());
  }
 
  public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
  {
  }

  public function preDispatch(Zend_Controller_Request_Abstract $request)
  {
  }

  public function postDispatch(Zend_Controller_Request_Abstract $request)
  {
		if(!$this->run)
		{
			$this->run = true;
			if(is_file($this->template->getPath('config.php')))
			{
				$config = require($this->template->getPath('config.php'));
				if(!empty($config[$this->layout->getLayout()]))
				foreach($config[$this->layout->getLayout()] as $key => $area)
				{
					if(!empty($area))
					foreach($area as $widget)
					{
						$widget = is_array($widget)?$widget:array($widget);
						$this->view->placeholder($key)->append(
							Core_Widget::getWidget(array_shift($widget))->setOption($widget)->render());
					}
				}
			}
		}
  }

  public function dispatchLoopShutdown()
  {
  }
}